<!-- 新增分区 -->
<template>
  <div>
    <el-dialog title="添加" :visible.sync="dialogShow" width="1100px" :close-on-click-modal="false" :close-on-press-escape="false">
      <form-common :filed-list="contractLeaseList" ref="infoForm" @selectChange="selectChange"></form-common>

      <template v-if="contractType == 'ZL' || contractType == 'TCCYY'">
        <div class="flex justify-between margin-bottom-15">
          <span class="font-size-16 font-weight-700">营销成本</span>
          <el-button type="primary" size="mini" @click="addCost" class="el-button-reset">添加营销成本</el-button>
        </div>
        <div v-for="(item, index) in costList" :key="item.guid" class="padding-bottom-10 fill-box relative-box" :class="index < costList.length - 1 ? 'border-b-line margin-bottom-30' : ''">
          <form-common :filed-list="item.filedList" :ref="`cost${index}`"></form-common>
          <el-button icon="el-icon-delete" class="color-red delete-btn" type="text" @click="deleteCost(index)"></el-button>
        </div>
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false" class="el-button-reset">取 消</el-button>
        <el-button type="primary" @click="confirmFn">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import formCommon from '@g/components/form/formCommon.vue';
  import { contractLeaseList, contractDyyList, contractAdList, contractSpaceList, contractEquipmentList, contractOtherGatherList, addContractLeaseCostList } from '../form.js';
  import { guid, setFiledVal } from '@/common/js/utils';
  import Bus from '@js/bus.js';
  import { apiPaysonList, apiActivitySpaceList } from '../../../../api/contract';
  import { apiPactConstant } from '@a/index';

  export default {
    props: {
      contractType: {
        type: String,
        default: '',
      },
      tableList: {
        type: Array,
        default: () => {
          return [];
        },
      },
      //基本信息中的项目key 合同开始时间 结束时间
      relevanceParam: {
        type: Object,
        default: () => {
          return {};
        },
      },
      //选择资产的数据源 商铺 广告 停车场 临时场地
      optionMap: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },

    data() {
      return {
        dialogShow: false,
        contractLeaseList: [],
        costList: [],
        model: {},
      };
    },

    watch: {
      tableList: {
        deep: true,
        handler(val) {
          this.setAllowRentSapceList();
        },
      },
      optionMap: {
        deep: true,
        handler(val) {
          this.setAssetOption();
        },
      },
    },

    methods: {
      //添加时初始化
      async init(type) {
        this.dialogShow = true;
        this.model = {};
        this.costList = [];
        if (type == 'add') {
          this.initFiledVal();
          this.setAllowRentSapceList();
        }
        await this.$nextTick(() => {});
        this.$refs.infoForm.clearValidateForm();
      },

      //保存
      confirmFn() {
        let costFiledList = []; //事项补贴
        let model = this.$refs.infoForm.validateForm(); //基本信息
        if (!model) return;

        let assetObj = this.setAssetName(model.assetKey);
        model.assetName = assetObj.assetName;
        model.assetCode = assetObj.assetCode;
        model.assetType = assetObj.assetType;
        if (this.contractType == 'ZL') {
          model.buildingArea = assetObj.buildingArea;
          model.chargeArea = assetObj.chargeArea;
          model.shareArea = assetObj.shareArea;
        }

        //只有租赁 ｜ 代运营合同有营销成本
        if (this.contractType == 'ZL' || this.contractType == 'TCCYY') {
          if (this.costList.length > 0) {
            this.costList.forEach((item, index) => {
              let formName = 'cost' + index;
              let model = this.$refs[formName][0].validateForm();
              costFiledList.push(model);
            });
            //校验添加的事项
            for (let i = 0; i < costFiledList.length; i++) {
              if (!costFiledList[i]) return;
            }

            let deepCloneCostList = this.lodash.cloneDeep(costFiledList);
            let noRepetCostList = this.lodash.uniqBy(deepCloneCostList, 'rentFreeItem'); //事项补贴去重
            noRepetCostList.forEach(item => (item.amount = 0));
            //把事项相同的金额加起来放入去重后的对象中
            costFiledList.forEach(oldCost => {
              noRepetCostList.forEach(newCost => {
                if (oldCost.rentFreeItem == newCost.rentFreeItem) {
                  newCost.amount += Number(oldCost.amount);
                }
              });
            });

            noRepetCostList.forEach(item => {
              model[item.rentFreeItem] = item.amount;
            });
            model.discountRentList = costFiledList; //把事项补贴和基本信息组合起来
          }
        }

        this.dialogShow = false;
        this.$emit('confirmAddItem', model);
      },

      //添加营销成本
      addCost() {
        let filedList = this.lodash.cloneDeep(addContractLeaseCostList);
        this.costList.push({
          guid: guid(),
          filedList: filedList,
        });
      },

      //添加营销成本
      editCost() {
        this.dialogShow = true;
      },

      //删除营销成本
      deleteCost(index) {
        this.costList.splice(index, 1);
      },

      //编辑营销成本字段返显
      editItem() {
        this.contractLeaseList[0].traggerEdit = guid(); //用于编辑时触发表单的重新渲染，因为重复点击编辑不修改任何内容的时候无法监听到
        setFiledVal(this.contractLeaseList, this.model);
        this.contractType == 'LSCD' && this.getAreaSpaceList();
        this.unshiftRentSapceList();

        //只有租赁 ｜ 代运营合同有营销成本
        if (this.contractType == 'ZL' || this.contractType == 'TCCYY') {
          this.model.discountRentList.forEach(item => {
            let filedList = this.lodash.cloneDeep(addContractLeaseCostList);
            filedList[0].traggerEdit = ''; //用于编辑时触发表单的重新渲染，因为重复点击编辑不修改任何内容的时候无法监听到
            setFiledVal(filedList, item);
            this.costList.push({
              guid: guid(),
              filedList: filedList,
            });
          });
        }
      },

      //初始化表单字段为空
      initFiledVal() {
        this.contractLeaseList.forEach(item => {
          item.bindFieldVal = '';
        });
      },

      //可租空间不可重复选择
      setAllowRentSapceList() {
        let choseList = [];
        this.tableList.forEach(item => {
          choseList.push(item.assetKey);
        });
        this.contractLeaseList.forEach(item => {
          if (item.bindFieldName == 'assetKey') {
            item.optionList.forEach(option => {
              if (choseList.indexOf(option.primaryKey) > -1) {
                option.ifCanChecked = false;
              } else {
                option.ifCanChecked = true;
              }
            });
          }
        });
      },

      //可租空间编辑时 要手动把之前 选过的option 的 ifCanChecked字段置为true让其显示
      unshiftRentSapceList() {
        this.contractLeaseList.forEach(item => {
          if (item.bindFieldName == 'assetKey') {
            item.optionList.forEach(option => {
              if (option.primaryKey == this.model.assetKey) {
                option.ifCanChecked = true;
              }
            });
          }
        });
      },

      //选择资产(可租空间 ｜ 广告位 ｜ 活动空间 ｜ 收入类型)要把code 和 name传给后台
      setAssetName(assetKey) {
        let assetObj = {};
        let txtName = '';
        let codeName = '';
        let typeName = '';
        let assetType = '';
        this.contractLeaseList.forEach(item => {
          if (item.bindFieldName == 'assetKey') {
            assetObj = item.optionList.find(option => (option.chargeItemKey ? option.chargeItemKey == assetKey : option.primaryKey == assetKey));
          }
        });
        if (this.contractType == 'ZL') {
          txtName = 'shopNumber';
          codeName = 'shopCode';
          typeName = 'spaceType';
        } else if (this.contractType == 'TCCYY') {
          txtName = 'parkName';
          codeName = 'parkCode';
          assetType = '101';
        } else if (this.contractType == 'GGZL') {
          txtName = 'locationDesc';
          codeName = 'assetCode';
          assetType = '102';
        } else if (this.contractType == 'LSCD') {
          txtName = 'name';
          codeName = 'code';
          typeName = 'targetType';
        } else if (this.contractType == 'WRSB' || this.contractType == 'QTSR') {
          txtName = 'chargeItemAliasName';
          codeName = 'chargeItemCode';
        }
        let target = {
          assetType: assetType || assetObj[typeName],
          assetCode: assetObj[codeName],
          assetName: assetObj[txtName],
        };
        if (this.contractType == 'ZL') {
          target.buildingArea = assetObj.buildingArea;
          target.chargeArea = assetObj.cadArea;
          target.shareArea = assetObj.shareArea;
        }
        return target;
      },

      //赋值 资产 | 区域 下拉框数据源
      setAssetOption() {
        let listName = this.contractType == 'ZL' ? 'shopList' : this.contractType == 'TCCYY' ? 'parkList' : 'adList';
        this.contractLeaseList.forEach(ele => {
          if (ele.bindFieldName == 'assetKey') {
            if (this.contractType == 'ZL' || this.contractType == 'TCCYY' || this.contractType == 'GGZL') {
              ele.optionList = this.optionMap[listName] || [];
            }
          }
          if (ele.bindFieldName == 'partitionKey') {
            ele.optionList = this.optionMap.areaList || [];
          }
        });
      },

      //表单事件
      async selectChange(data) {
        // 判断时间
        if (data.filedName == 'rentStartDate' || data.filedName == 'rentEndDate') {
          let timestamp = data.model.rentEndDate - data.model.rentStartDate;
          if (timestamp < 0) {
            if (data.filedName == 'rentEndDate') {
              this.$message.warning('结束时间应大于开始时间');
              data.model.rentEndDate = '';
            }
            if (data.filedName == 'rentStartDate' && data.model.rentEndDate) {
              this.$message.warning('结束时间应大于开始时间');
              data.model.rentEndDate = '';
            }
          }
        }
        //临时场地合同的区域选择级连活动空间
        if (data.filedName == 'partitionKey') {
          let res = await apiActivitySpaceList({ projectKey: this.relevanceParam.projectKey, spacePartitionKey: data.filedVal });
          res.rows.forEach(item => (item.ifCanChecked = true));
          data.cbList('assetKey', res.rows);
        }
      },

      //基础信息字段初始化
      initBaseInfoFiledList() {
        if (this.contractType == 'ZL') {
          this.contractLeaseList = contractLeaseList;
        } else if (this.contractType == 'TCCYY') {
          this.contractLeaseList = contractDyyList;
        } else if (this.contractType == 'GGZL') {
          this.contractLeaseList = contractAdList;
        } else if (this.contractType == 'LSCD') {
          this.contractLeaseList = contractSpaceList;
        } else if (this.contractType == 'WRSB') {
          this.contractLeaseList = contractEquipmentList;
        } else if (this.contractType == 'QTSR') {
          this.contractLeaseList = contractOtherGatherList;
        }
      },

      //接受兄弟传值
      initBus() {
        Bus.$on('costItem', async data => {
          console.log(data);
          await this.init();
          this.model = data;
          this.editItem();
        });
      },

      //临时场地合同的区域数据源
      async getAreaSpaceList() {
        let res = await apiActivitySpaceList({ projectKey: this.relevanceParam.projectKey, spacePartitionKey: this.model.partitionKey });
        res.rows.forEach(item => (item.ifCanChecked = true));
        this.contractLeaseList.forEach(ele => {
          if (ele.bindFieldName == 'assetKey') {
            ele.optionList = res.rows || [];
          }
        });
      },

      //常量
      async getConstant() {
        let res = await apiPactConstant();
        this.contractLeaseList.forEach(ele => {
          //付款方式
          if (ele.bindFieldName == 'paymentMethod') {
            ele.optionList = res.paymentMethod || [];
          }
        });
        addContractLeaseCostList.forEach(ele => {
          //补贴类型
          if (ele.bindFieldName == 'rentFreeItem') {
            ele.optionList = res.discountType || [];
          }
        });
      },

      //收入类型
      async getChargeItemList(filedName) {
        let res = await apiPaysonList({ contractType: this.contractType });
        this.contractLeaseList.forEach(item => {
          if (item.bindFieldName == 'assetKey') {
            item.optionList = res.rows || [];
          }
        });
      },
    },

    created() {
      this.initBus();
      this.initBaseInfoFiledList();

      if (this.contractType == 'WRSB' || this.contractType == 'QTSR') {
        this.getChargeItemList();
      }

      this.getConstant();
    },

    components: { formCommon },
  };
</script>
<style lang="scss" scoped>
  .delete-btn {
    position: absolute;
    top: 0;
    right: 0;
  }
  ::v-deep .el-button--text {
    font-size: 18px;
  }
</style>
